﻿using HyEduOnline.Entities;
using HyEduOnline.Models;
using HyEduOnline.Server.Admin;
using HyEduOnline.Server.Common;
using HyEduOnline.Server.Student;
using HyEduOnline.Server.Teacher;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSite.Areas.WebApi.Controllers;
using WebSite.Models;
using System.Net;
using System.Net.Http;
using System.Text;


namespace WebSite.Areas.WebApi.Controllers
{




    public class EmailExtController : EmailController
    {

        private EmailContentDAO EmDao = new EmailContentDAO();
        private EmailAttchmentDAO AtDao = new EmailAttchmentDAO();
        private EmailDAO MaDao = new EmailDAO();
        private EmailReciverDAO ReDao = new EmailReciverDAO();
        private VwEmailDAO VwEmailDAO = new VwEmailDAO();


        private const string FilePath = "/Upload/EmailAttchment/";//上传的邮件附件的存储路径

        private string CurrentFileName = "";  //实时文件名
        private int AttchmentType ;//附件的类型





        [HttpPost]
        public JsonResult EmailAttchmentUpload(string qqfile)
        {
            string realAttchmentName = qqfile; //文件的真实名字
            string currentUserIDString = null;  //当前登录用户的工号
            currentUserIDString = GetCurrentUserNoString();//当前用户编号
            

            string fileName = DateTime.Now.ToString("ddHHmmssff");//名称
            CurrentFileName = fileName;
            string fileType = qqfile.Substring(qqfile.LastIndexOf("."));//获取附件的扩展名类型
            string webFile = FilePath + currentUserIDString + "/UploadFile/" + fileName + fileType;//服务器端路径          

            string uploadPath = "";
            uploadPath = Server.MapPath(FilePath + currentUserIDString + "/UploadFile/");//物理存储路径
            Session["uploadPath"] = webFile;
            try
            {
                //若不存在当前目录则创建
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                //流存储
                using (var inputStream = Request.InputStream)
                {
                    using (var flieStream = new FileStream(Server.MapPath(webFile), FileMode.Create))
                    {
                        inputStream.CopyTo(flieStream);
                    }
                }
                return Json(new { success = true, trueAttachName = realAttchmentName, AttachwebFile = webFile });//返回附件的附件名，附件的服务器路径
           

            }
            catch (Exception)
            {

                return Json(new { fail = true });
            }
            
        }

        #region 处理附件的类型
        /// <summary>
        /// 转换处理附件的类型  
        /// </summary>
        /// <param name="fileName">附件名</param>
        public void forMatAttchmentType(string fileName)
        {
            string attchmentExtension = fileName.Substring(fileName.LastIndexOf("."));  //获取文件的扩展名
            switch (attchmentExtension)
            {
                case ".jpeg":
                    AttchmentType = 1;
                    break;
                case ".jpg":
                    AttchmentType = 1;
                    break;
                case ".gif":
                    AttchmentType = 1;
                    break;
                case ".png":
                    AttchmentType = 1;  //设置图片的附件类型为1
                    break;
                case ".doc":
                    AttchmentType = 2;
                    break;
                case ".docx":
                    AttchmentType = 2;
                    break;
                case ".docm":
                    AttchmentType = 2;//设置文档附件类型为2
                    break;
                case ".xls":
                    AttchmentType = 3;
                    break;
                case ".xlsx":
                    AttchmentType = 3; //设置表格附件的类型为3
                    break;
                case ".pptx":
                    AttchmentType = 4;
                    break;
                case ".ppt":
                    AttchmentType = 4; //设置PPT附件的类型为4
                    break;
                case ".zip":
                    AttchmentType = 5;
                    break;
                case ".rar":
                    AttchmentType = 5;//设置压缩附件的类型为5
                    break;
                case ".pdf":
                    AttchmentType = 6; //设置pdf附件的类型为6
                    break;
                case ".wps":
                    AttchmentType = 7; //设置wps附件的类型为7
                    break;
                case ".et":
                    AttchmentType = 8; //设置et附件的类型为8
                    break;
                case ".dps":
                    AttchmentType = 9;//设置dps附件的类型为9
                    break;
                case ".txt":
                    AttchmentType = 10; //设置文本附件的类型为10
                    break;
                default:
                    break;
            }

        } 
        #endregion


        #region 更新邮件+UpDateMail(发送和再次存为草稿）

        public void UpDateMail(NewMail mail)
        {

            ReciverData recvData = new ReciverData();

            recvData = SubData(mail);//将转换后的收件人字符保存到ReciverData类里面   


            //草稿邮件的重发或者从新存为草稿
            TbEmail tbMp = MaDao.GetByID(mail.Id);
            tbMp.SSenderNo = GetCurrentUserNoString();//当前用户编号;
            tbMp.SSenderName = GetCurrentUserNameString();//当前用户姓名
/**
            switch (Session["UserType"].ToString())
            {
                case "0":
                    tbMp.SSenderNo = frontCurrentStu.GetNo();
                    tbMp.SSenderName = frontCurrentStu.GetUserName();
                    break;
                case "1":
                    tbMp.SSenderNo = frontCurrentTea.GetNo();
                    tbMp.SSenderName = frontCurrentTea.GetUserName();
                    break;
                case "2":
                    tbMp.SSenderNo = FrontUserInfo.GetUserNo();
                    tbMp.SSenderName = FrontUserInfo.GetUserName();
                    break;
                default:
                    break;
            }*/

            tbMp.SRecName = recvData.SNamesString;
            tbMp.SRecNo = recvData.SRecNoString;
            tbMp.STitle = mail.STitle;
            tbMp.DSendtime = DateTime.Now;
            tbMp.IEmailType = mail.IEmailType;
            tbMp.IIsDestroyAffterRead = mail.IIsDestroyAffterRead;
            tbMp.IIsCancel = mail.IIsCancel;
            tbMp.SSendIp = mail.SSendIp;
            tbMp.IIsDeleteFlag = mail.IIsDeleteFlag;

            if (mail.SAttachmentName != null)
            {
                tbMp.IIsExistAttchment = 1; //存在附件，置附件存在标志为1
            }
            else
            {
                tbMp.IIsExistAttchment = 0; //不存在附件，置附件存在标志为0
            }


            MaDao.Update(tbMp);//更新邮件信息

            //取取主表的id，关联邮件内容表、接收人表和附件表

            var id = tbMp.Id;

            //构建一个查询条件
            string whereClause;
            whereClause = "I_EmailId='" + id + "'";


            //更新接收人表

            TbEmailReciver tbRe = new TbEmailReciver();
            tbRe.IEmailId = id;
            tbRe.IIsRead = 0;//0表示为未读，1表示已读默认为未读
            //如果是一般邮件
            if (mail.IEmailType == 1)
            {
                //mail.SRecNo = null;
                //截断收件人姓名和编号的字符段
                string[] ReciversSNo = recvData.SNamesString.Split(new char[] { ';' });
                string[] ReciversSName = recvData.SRecNoString.Split(new char[] { ';' });
                //依次向收件人表插入收件人信息
                for (int i = 0; i < ReciversSName.Length - 1; i++)
                {
                    tbRe.SRecName = ReciversSNo[i];
                    tbRe.SRecNo = ReciversSName[i];
                    if (tbRe.SRecName != null && tbRe.SRecNo != null)
                    {
                        ReDao.Insert(tbRe);
                    }

                }
            }


            //向附件表中插入对应的数据 

            TbEmailAttchment tbAttach = new TbEmailAttchment();
            tbAttach.IEmailId = id;
            if (mail.SAttachmentName != null)  //文件名不空
            {
                string tempAttach = mail.SAttachmentName;   //附件名字符串
                string tempUrls = mail.SUrl;//附件的路径字符串
                string[] AttachNames = tempAttach.Split(new char[] { ';' });
                string[] AttachUrls = tempUrls.Split(new char[] { ';' });

                for (int i = 1; i < AttachNames.Length; i++)
                {
                    if (AttachNames[i] != "" && AttachNames[i] != null)
                    {
                        tbAttach.SAttachmentName = AttachNames[i];
                        forMatAttchmentType(AttachNames[i]);
                        tbAttach.IType = AttchmentType;  //附件的类型
                        tbAttach.SUrl = AttachUrls[i]; //服务器路径
                        AtDao.Insert(tbAttach);
                    }
                }
            }


            ////向附件表中插入对应的数据,先判断是否主键Id对应的附件是否有字段
            //TbEmailAttchment tbAttach = new TbEmailAttchment();
            
            //if (mail.SAttachmentName != null)  //文件名不空
            //{
            //    tbAttach.SAttachmentName = mail.SAttachmentName; //附件的真实名字
            //    tbAttach.IEmailId = id;
            //    forMatAttchmentType(mail.SAttachmentName);
            //    tbAttach.IType = AttchmentType;  //附件的类型 
            //    tbAttach.SUrl = mail.SUrl; //服务器路径
            //}
            


            ////todo，更新还有问题，当开始有附件，后来撤销附件时要删除
            ////还要考虑上传了多个附件的问题
            //if (tbAttach.SAttachmentName != null)//前提是有附件
            //{
            //    TList<TbEmailAttchment> EmialAttachList = new EmailAttchmentDAO().GetByPage(whereClause, 0, int.MaxValue);
                
            //    if (EmialAttachList.Count > 0)  //存在附件
            //    {
            //        if (!EmialAttachList.Contains(tbAttach))//不存在该附件
            //        { 
            //            AtDao.Insert(tbAttach);

            //        }  
            //    }
            //    else  //不存在附件
            //    {
            //        AtDao.Insert(tbAttach);
            //    }
            //}


            //向内容表中插入数据
            TbEmailContent tbCon = new TbEmailContent();
            tbCon.IEmailId = id;
            tbCon.SContent = mail.SContent;
            if (tbCon.SContent != null)
            {
                TList<TbEmailContent> TbEc = new EmailContentDAO().GetByPage(whereClause, 0, int.MaxValue);
                if (TbEc.Count > 0)
                {
                    tbCon.Id = TbEc[0].Id;  //取第一个数据进行更新

                    EmDao.Update(tbCon);
                }
                else
                {
                    EmDao.Insert(tbCon);
                }

            }



        }
        #endregion



        #region 截取收件人的姓名和编号并从新拼凑成新的收件人姓名和收件人编号字符串
        /// <summary>
        /// 截取收件人的姓名和编号，并从新拼凑成新的收件人姓名和收件人编号
        /// </summary>
        /// <param name="mail"> 前台传来的NodeValue</param>
        /// <returns></returns>
        public ReciverData SubData(NewMail mail)
        {
            ReciverData tempData = new ReciverData();
            string tempSNames = null;//存储收件人姓名串
            string tempSNo = null;//存储收件人编号
            mail.SRecNo = ';' + mail.SRecNo;
            var Recver = mail.SRecNo;//Recver包含了收件人的姓名和编号

            try
            {
                string[] Recivers = Recver.Split(new char[] { ';' });
                //先按照“;”号截取每一个收件人
                for (int item1 = 1; item1 < Recivers.Length - 1; item1++)
                {
                    string[] SubReciver = Recivers[item1].Split(new char[] { '<' });
                    //再按照“<”号截取每一个收件人的姓名和编号
                    for (int item2 = 1; item2 < SubReciver.Length; item2++)
                    {

                        tempSNames += SubReciver[0].ToString() + ";";
                        string recNoBefore = SubReciver[1].ToString();

                        string[] recNoAfter = recNoBefore.Split(new char[] { '>' });

                        tempSNo += recNoAfter[0].ToString() + ";";

                    }
                }
                tempData.SNamesString = tempSNames;
                tempData.SRecNoString = tempSNo;
                return tempData;
            }
            catch (Exception e)
            {
                
                throw e.InnerException;
            }
            

        }
        #endregion



        #region 发送邮件+SendEmail(NewMail mail)：当向数据库第一次插入的邮件信息

        [ValidateInput(false)]
        public void SendEmail(NewMail mail)
        {

            ReciverData recvData = new ReciverData();

            recvData = SubData(mail);//将转换后的收件人字符保存到ReciverData类里面


            //向主表中插入数据
            //test11.13
            TbEmail tbMp = new TbEmail();
            tbMp.SSenderNo = GetCurrentUserNoString();//当前用户编号;
            tbMp.SSenderName = GetCurrentUserNameString();//当前用户姓名
/*
            switch (Session["UserType"].ToString())
            {
                case "0":
                    tbMp.SSenderNo = frontCurrentStu.GetNo();
                    tbMp.SSenderName = frontCurrentStu.GetUserName();
                    break;
                case "1":
                    tbMp.SSenderNo = frontCurrentTea.GetNo();
                    tbMp.SSenderName = frontCurrentTea.GetUserName();
                    break;
                case "2":
                    tbMp.SSenderNo = FrontUserInfo.GetUserNo();
                    tbMp.SSenderName = FrontUserInfo.GetUserName();
                    break;
                default:
                    break;
            }*/

            tbMp.STitle = mail.STitle;
            tbMp.DSendtime = DateTime.Now;
            tbMp.IEmailType = mail.IEmailType;
            tbMp.IIsDestroyAffterRead = mail.IIsDestroyAffterRead;
            tbMp.IIsCancel = mail.IIsCancel;
            tbMp.SSendIp = mail.SSendIp;
            tbMp.IIsDeleteFlag = mail.IIsDeleteFlag;



            tbMp.SRecName = recvData.SNamesString;
            tbMp.SRecNo = recvData.SRecNoString;
            if (mail.SAttachmentName != null)
            {
                tbMp.IIsExistAttchment = 1; //存在附件，置附件存在标志为1
            }
            else
            {
                tbMp.IIsExistAttchment = 0; //不存在附件，置附件存在标志为0
            }
            MaDao.Insert(tbMp);

            //取得tbMp的id
            var id = tbMp.Id;
            //向接收者表表中插值-
            TbEmailReciver tbRe = new TbEmailReciver();

            tbRe.IEmailId = id;
            tbRe.IIsRead = 0;//0表示为未读，1表示已读默认为未读

            if (mail.IEmailType == 1)
            {
                try
                {
                    //截断收件人姓名和编号的字符段
                    string[] ReciversSNo = recvData.SNamesString.Split(new char[] { ';' });
                    string[] ReciversSName = recvData.SRecNoString.Split(new char[] { ';' });
                    for (int i = 0; i < ReciversSName.Length - 1; i++)
                    {
                        tbRe.SRecName = ReciversSNo[i];
                        tbRe.SRecNo = ReciversSName[i];
                        if (tbRe.SRecName != null && tbRe.SRecNo != null)
                        {
                            ReDao.Insert(tbRe);
                        }

                    }

                }
                catch (Exception e)
                {

                    throw e;
                }
               
            }






            //向附件表中插入对应的数据 
                        
            TbEmailAttchment tbAttach = new TbEmailAttchment();
            tbAttach.IEmailId = id;
            if (mail.SAttachmentName != null)  //文件名不空
            {
                string tempAttach = mail.SAttachmentName;   //附件名字符串
                string tempUrls = mail.SUrl;//附件的路径字符串
                string[] AttachNames = tempAttach.Split(new char[] { ';' });
                string[] AttachUrls = tempUrls.Split(new char[] { ';' });
                
                for (int i = 1; i < AttachNames.Length; i++)
                {
                    if (AttachNames[i] !="" && AttachNames[i]!= null)
                    {
                        tbAttach.SAttachmentName = AttachNames[i];
                        forMatAttchmentType(AttachNames[i]);
                        tbAttach.IType = AttchmentType;  //附件的类型
                        tbAttach.SUrl = AttachUrls[i]; //服务器路径
                        AtDao.Insert(tbAttach);
                    }
                }
            }
            


            //向内容表中插入数据
            TbEmailContent tbCon = new TbEmailContent();
            tbCon.IEmailId = id;
            tbCon.SContent = mail.SContent;
            if (tbCon.SContent != null)
            {
                EmDao.Insert(tbCon);
            }

        }




        #endregion



        #region 删除选中的附件
        /// <summary>
        /// 删除选中的附件  add by yzp  11.22
        /// </summary>
        /// <param name="ID"></param>
        public void DeleteChoosenAttach(int ID)
        {
            try
            {
                TbEmailAttchment tempAttach = new EmailAttchmentDAO().GetByID(ID);
                if (tempAttach != null)
                {
                    string surl = tempAttach.SUrl;
                    System.IO.File.Delete(Server.MapPath(surl));//删除物理文件  
                    AtDao.Del(tempAttach);
                }
            }
            catch (Exception e)
            {

                throw e.InnerException;
            }

        } 
        #endregion



        #region 获取被选中邮件的所有附件
        /// <summary>
        /// 获取被选中邮件的所有附件
        /// </summary>
        /// <param name="emailId">被选中邮件的ID</param>
        /// <returns></returns>
        public JsonResult EmailAttachmentInfo(int emailId)
        {
            string WhereClause = "I_EmailID=" + emailId;
            TList<TbEmailAttchment> EmailAttchmentList = new EmailAttchmentDAO().GetByPage(WhereClause, 0, int.MaxValue);
            if (EmailAttchmentList.Count > 0)
            {
                return Json(EmailAttchmentList, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return null;
            }
        } 
        #endregion





        #region 查询收件箱+GetCurrentSysMail
        /// <summary>
        /// 收件箱
        /// </summary>
        /// <param name="firstResult">起始位置</param>
        /// <param name="pagesize">页面大小</param>
        /// <param name="orderBy">排序列</param>
        /// <param name="condition">筛选条件</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetCurrentSysMail(int firstResult, int pagesize, string orderBy, string condition)
        {
            orderBy = "DSendtime DESC";  //重置按发送时间排序，排序方式为降序
            string whereStr = HttpUtility.UrlDecode(condition);

            if (whereStr != "1=1")//收件箱，当传递过来的数据为S_Title like% %拼凑 加一个条件S_SenderName like
            {

                whereStr = whereStr.Substring(0, whereStr.Length - 1) + " or S_SenderName" + whereStr.Substring(9, whereStr.Length - 9);
            }


            //test11.13
           // string trueWhere = "s_recNo='" + FrontUserInfo.GetUserNo() + "'";//拼接当前用户编号
            string trueWhere = "s_recNo='" + GetCurrentUserNoString() + "'";//拼接当前用户编号
            if (!String.IsNullOrEmpty(whereStr))
            {
                trueWhere += " and " + whereStr;
            }


            VList<VwEmail> userList = VwEmailDAO.GetByPageVW(trueWhere, firstResult * pagesize, pagesize, orderBy, out totalCount);


           //test11.13
           // string unreadClause = "s_recNo='" + FrontUserInfo.GetUserNo() + "' and I_IsRead=0";
            string unreadClause = "s_recNo='" + GetCurrentUserNoString() + "' and I_IsRead=0";
            TList<TbEmailReciver> unreadList = new EmailReciverDAO().GetByPage(unreadClause, 0, int.MaxValue);

            int UnReadCount;//保存未读邮件的封数
            if (unreadList.Count <= 0)
            {
                UnReadCount = 0;//没有未读邮件的时候返回0
            }
            else
            {
                UnReadCount = unreadList.Count; //返回未读邮件封数
            }
            return this.Json(new
            {
                DataCount = totalCount,
                Data = userList,
                UnReadDataCount = UnReadCount//获未读邮件封数
            }, JsonRequestBehavior.AllowGet);


        }
        #endregion


        #region 查询发件箱+SenderCurrentSysMail
        /// <summary>
        /// 发件箱
        /// </summary>
        /// <param name="firstResult">起始值</param>
        /// <param name="pagesize">页面大小</param>
        /// <param name="orderBy">排序列</param>
        /// <param name="condition">筛选条件</param>
        /// <returns></returns>


        [HttpGet]
        public JsonResult SenderCurrentSysMail(int firstResult, int pagesize, string orderBy, string condition)
        {

            string SenderName = GetCurrentUserNameString();
            string SenderNo=GetCurrentUserNoString();
            orderBy = "DSendTime DESC";  //重置按发送时间排序，排序方式为降序

            string whereStr = HttpUtility.UrlDecode(condition);


            if (whereStr != "1=1")//发件箱，当传递过来的数据为S_Title like% % 拼接S_RecName like
            {

                whereStr = whereStr.Substring(0, whereStr.Length - 1) + " or S_RecName" + whereStr.Substring(9, whereStr.Length - 9);
            }

            //string trueWhere = "S_SenderNo='" + FrontUserInfo.GetUserNo() + "'and S_SenderName='"+FrontUserInfo.GetUserName()+"' and I_EmailType=1 and I_IsDeleteFlag=0";
            string trueWhere = "S_SenderNo='" +SenderNo + "'and S_SenderName='"+SenderName+"' and I_EmailType=1 and I_IsDeleteFlag=0";
            
            if (!String.IsNullOrEmpty(whereStr))
            {
                trueWhere += " and " + whereStr;
            }

            TList<TbEmail> reTurndata = EmailDAO.getByPageDataBase(firstResult, pagesize, orderBy, trueWhere, out totalCount);
            return this.Json(new
            {
                DataCount = totalCount,//返回总条数
                Data = reTurndata//返回查找对象集合
            }, JsonRequestBehavior.AllowGet);

        }
        #endregion


        #region 草稿箱+DraftCurrentSysMail
        /// <summary>
        /// 草稿箱
        /// </summary>
        /// <param name="firstResult">起始值</param>
        /// <param name="pagesize">页面大小</param>
        /// <param name="orderBy">排序列</param>
        /// <param name="condition">筛选条件</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult DraftCurrentSysMail(int firstResult, int pagesize, string orderBy, string condition)
        {
            string CurrentUserNo = GetCurrentUserNoString();
            orderBy = "DSendTime DESC";  //重置按发送时间排序，排序方式为降序
            string whereStr = HttpUtility.UrlDecode(condition);


            if (whereStr != "1=1")//Sitle或者SenderName//该处条件用于查询草稿（当传递过来的数据为S_Title like% %
            {

                whereStr = whereStr.Substring(0, whereStr.Length - 1) + " or S_RecName" + whereStr.Substring(9, whereStr.Length - 9);
            }
            string trueWhere = "S_SenderNo='" + CurrentUserNo + "'and I_EmailType=0";
            if (!String.IsNullOrEmpty(whereStr))
            {
                trueWhere += " and " + whereStr;
            }


            TList<TbEmail> reTurndata = EmailDAO.getByPageDataBase(firstResult, pagesize, orderBy, trueWhere, out totalCount);
            return this.Json(new
            {
                DataCount = totalCount,
                Data = reTurndata
            }, JsonRequestBehavior.AllowGet);

        }
        #endregion



        #region 获取邮件的详细信息+DetailMail
        public JsonResult DetailMail(int id)
        {
            string CurrentUserNo = GetCurrentUserNoString();//获取当前用户的编号
            //string CurrentUserNo = FrontUserInfo.GetUserNo();//获取当前用户的编号
            // string CurrentUserName = FrontUserInfo.GetUserName();//获取当前用户的姓名GetCurrentUserNameString

            string CurrentUserName = GetCurrentUserNameString();//获取当前用户的姓名

            //1,获取主表的信息
            TbEmail MainEmail = new EmailDAO().GetByID(id);



            string whereClauseReciver = "I_EmailID='" + id + "' and  S_RecNo='" + CurrentUserNo + "'";

            TList<TbEmailReciver> EmailReciver = new EmailReciverDAO().GetByPage(whereClauseReciver, 0, int.MaxValue);


            //获取内容表的信息


            string whereClause = "I_EmailID=" + id ;
            TList<TbEmailContent> EmailContent = new EmailContentDAO().GetByPage(whereClause, 0, int.MaxValue);
            string ext = "";//获取当前的内容
            if (EmailContent.Count > 0)
            {
                TbEmailContent temp = EmailContent[0];

                if (temp != null)
                {

                    ext = temp.SContent;
                }
            }


            // 更新收件人表的阅读状态
            string whereClause1 = "I_EmailID=" + id ;
            var EmailId = id;
            TList<TbEmailReciver> EmailRec = new EmailReciverDAO().GetByPage(whereClause1, 0, int.MaxValue);
            if (EmailRec.Count > 0)
            {
                //在收件人列表中查找当前用户，并更新阅读状态
                for (int i = 0; i < EmailRec.Count; i++)
                {
                    if (EmailRec[i].SRecNo == CurrentUserNo)
                    //if (EmailRec[0].SRecNo == Session["UserNo"].ToString())
                    {
                        EmailRec[i].IIsRead = 1;
                        ReDao.Update(EmailRec[i]);
                        break;
                    }

                }
            }

            return this.Json(new { Data = MainEmail, Ext = ext, CurrentUserNames = CurrentUserName, CurrentUserNos = CurrentUserNo }, JsonRequestBehavior.AllowGet);

        }
        #endregion






        #region 邮件的删除+DeleteEmail
        public int DeleteEmail(string ids, int EmailKind)
        {
          // 修改test11.13
            //string CurrentUserNo = FrontUserInfo.GetUserNo();//当前用户
            string CurrentUserNo = GetCurrentUserNoString();//当前用户
            int tempEmailKind = EmailKind;//获取前台传过来的发件箱/草稿箱/收件箱类型数据
            try
            {
                string[] SIds = ids.Split(new char[] { ',' });

                foreach (var SId in SIds)
                {
                    int IId = int.Parse(SId);//对应表的Id
                    TbEmail MianList = new EmailDAO().GetByID(IId);//获取到主表Id对应的那条数据

                    //to do test1
                    if (tempEmailKind == 1)//tempEmailKind == 1//发件箱或草稿箱
                    {



                        if (MianList.IEmailType == 0)//0表示草稿箱
                        {
                            Delall(MianList, IId);
                        }
                        else//当其实发件箱的时候
                        {
                            MianList.IIsDeleteFlag = 1;

                            MaDao.Update(MianList);
                            string whereClauseRec = "I_EmailID=" + IId ;
                            //从收件人表中获取该发送者条数的邮件记录
                            TList<TbEmailReciver> ReDel = new EmailReciverDAO().GetByPage(whereClauseRec, 0, int.MaxValue);
                            //
                            if (ReDel.Count <= 0)
                            {

                                Delall(MianList, IId);//调用删除Email表,reciver表,Content,attachment表
                            }
                        }

                    }
                    else//tempEmailKind==0此时为收件箱
                    {
                        string whereClause = "I_EmailID='" + IId + "' and S_RecNo='" + CurrentUserNo + "'";
                        TList<TbEmailReciver> ReDel = new EmailReciverDAO().GetByPage(whereClause, 0, int.MaxValue);
                        if (ReDel.Count > 0)
                        {
                            var tempCount = ReDel.Count;
                            ReDao.Del(ReDel[0]);
                            if (((tempCount - 1) <= 0) && MianList.IIsDeleteFlag == 1)
                            {
                                Delall(MianList, IId);//调用删除Email表,reciver表,Content,attachment表
                            }
                        }

                    }

                }
                return 1;
            }
            catch (Exception ex)
            {
                return 0;
            }
            return 0;
        }
        #endregion




        #region 删除函数+Delall
        /// <summary>
        /// 删除TbEmail的一条信息，TBEmailReciver,TBEmailContent,TBEmailAttachment
        /// </summary>
        /// <param name="MianList">邮件主表</param>
        /// <param name="IId">传过来对应的Email表的ID</param>
        public void Delall(TbEmail MianList, int IId)
        {
            string whereClauseRec = "I_EmailID="+ IId ;
            MaDao.Del(MianList);
            //从附件表中删除附件记录
            TList<TbEmailAttchment> TbEa = new EmailAttchmentDAO().GetByPage(whereClauseRec, 0, int.MaxValue);
            //如果该邮件存在附件或者存在多个邮件，则逐一删除
            if (TbEa.Count > 0)
            {
                for (int i = 0; i < TbEa.Count; i++)
                {
                    TbEmailAttchment TempAtt = TbEa[i];
                    string url = TempAtt.SUrl; //获取附件的路径
                    System.IO.File.Delete(Server.MapPath(url));//删除物理文件  修改于10.22 by yzp
                    AtDao.Del(TempAtt);
                }
            }

            //从内容表中删除该邮件的内容记录
            TList<TbEmailContent> TbEc = new EmailContentDAO().GetByPage(whereClauseRec, 0, int.MaxValue);
            if (TbEc.Count > 0)
            {
                TbEmailContent TempCon = TbEc[0];
                EmDao.Del(TempCon);
            }
        }
        #endregion





        #region 获取收件人的基本信息+GetAllTypeUser
        /// <summary>
        /// 来自客户端的通用用户名查询，返回like的前10项
        /// </summary>
        /// <param name="Type">用户类别,1为学生,2为教师,3为管理员</param>
        /// <param name="Name"></param>
        /// <returns></returns>
        public JsonResult GetAllTypeUser(int Type, string Name)
        {

            int tCount = 0;
            IList<CommonUser> tpResult = new List<CommonUser>();  //CommonUser为一个公共用户类

            switch (Type)
            {
                case 1:
                    IList<TbStudents> tpL1 = new StudentsDAO().getByPageDataBase(0, 10, "ID ASC", "S_Name like '%" + Name.Trim() + "%'", out tCount);
                    if (tpL1.Count > 0)
                    {
                        foreach (var item1 in tpL1)
                        {
                            CommonUser item = new CommonUser();
                            item.Id = item1.Id;
                            item.Type = 1;//学生
                            item.SName = item1.SName;
                            item.SNo = item1.SNo;
                            tpResult.Add(item);
                        }

                    }
                    break;
                case 2:
                    IList<TbTeachers> tpL2 = new TeachersDAO().getByPageDataBase(0, 10, "ID ASC", "S_TeaName like '%" + Name.Trim() + "%'", out tCount);
                    if (tpL2.Count > 0)
                    {
                        foreach (var item2 in tpL2)
                        {
                            CommonUser item = new CommonUser();
                            item.Id = item2.Id;
                            item.Type = 2;//教师
                            item.SName = item2.STeaName;
                            item.SNo = item2.STeaNo;
                            tpResult.Add(item);
                        }

                    }
                    break;
                case 3:

                    IList<TbSysUser> tpL3 = new SysUserDAO().getByPageDataBase(0, 10, "ID ASC", "S_TrueName like '%" + Name.Trim() + "%'", out tCount);
                    if (tpL3.Count > 0)
                    {
                        foreach (var item3 in tpL3)
                        {
                            CommonUser item = new CommonUser();
                            item.Id = item3.Id;
                            item.Type = 3;//系统用户
                            item.SName = item3.STrueName;
                            item.SNo = item3.SUserName;
                            tpResult.Add(item);
                        }

                    }
                    break;


                default:
                    break;
            }

            return Json(tpResult, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region ys
        //test11.13
        //识别当前的登录用户类型当前用户的登录类型
        public string GetCurrentUserNoString()
        {
            string CurrentUserNoString = "";
            switch (Session["UserType"].ToString())
            {
                case "0":  //当前登录用户的类型为学生
                    CurrentUserNoString = frontCurrentStu.GetNo();
                    break;
                case "1": //当前登录用户的类型为教师
                    CurrentUserNoString = frontCurrentTea.GetNo();
                    break;
                case "2"://当前登录用户的类型为管理员GetUserName
                    CurrentUserNoString = FrontUserInfo.GetSysUserName();
                    break;
                default:
                    break;
            }

            return CurrentUserNoString;
        }

        //识别当前的登录用户名
        public string GetCurrentUserNameString()
        {
            string CurrentUserNameString = "";
            switch (Session["UserType"].ToString())
            {
                case "0":  //当前登录用户的类型为学生
                    CurrentUserNameString = frontCurrentStu.GetUserName();
                    break;
                case "1": //当前登录用户的类型为教师
                    CurrentUserNameString = frontCurrentTea.GetUserName();
                    break;
                case "2"://当前登录用户的类型为管理员GetUserName
                    CurrentUserNameString = FrontUserInfo.GetSysUserTureName();
                    break;
                default:
                    break;
            }

            return CurrentUserNameString;
        } 
        #endregion


    }
}

